<template>
  <el-menu class="top-bar" mode="horizontal" router>
    <el-menu-item index="/">首页</el-menu-item>
    <el-menu-item index="/postvideo">投稿视频</el-menu-item>
    <el-menu-item index="/about">每日排行</el-menu-item>
    <el-menu-item index="/login">登录</el-menu-item>
    <el-menu-item index="/register">注册</el-menu-item>
    <el-menu-item id="user" >
      <i class="el-icon-user"></i>
      <el-dropdown>
        <el-avatar class="el-dropdown-link" src="" id="nickname">请登录</el-avatar>

        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item>
            <el-button type="primary"  @click="onLogout" style="width:100%;">退出</el-button>
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </el-menu-item>
  </el-menu>
</template>

<script>
import * as loginAPI from '@/api/login/';
import logoutAPI from '@/api/logout/'

export default {
  name: 'NavBar',
  data() {
    return {
      user: {
        id: '',
        user_name: '',
        nickname: '',
        avatar: '',
      }
    };
  },
  mounted() {
    this.getme()
  },
  methods: {
    getme() {
      loginAPI.getUserMe().then((res) => {
        if (res.status == 0) {
          if (res.data.avatar != "")
          {
            document.getElementById('nickname').src = res.data.avatar
          }
          else {
            document.getElementById('nickname').innerText = res.data.nickname
          }
        }
      }).catch(() => {
        this.$notify.error({
          title: '当前是游客状态',
        });
      });
    },
    onLogout() {
      logoutAPI().then((res) => {
        if (res.status > 0) {
          this.$notify.error({
            title: '退出失败',
            message: res.msg,
          });
        } else {
          this.$router.go(0);
          this.$router.push({ path: '/login'})
          this.$notify({
            title: '退出成功',
            type: 'success',
          });
        }
      }).catch((error) => {
        this.$notify.error({
          title: '网路错误，或者服务器宕机',
          message: error,
        });
      });
    }
  },
}

</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.top-bar {
  margin-bottom: 30px
}
#user {
  float: right;
}
</style>
